<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 15:22:10
 * @LastEditTime: 2023-11-10 15:24:49
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Traits\AttachmentTrait;
use App\Traits\SoftDeletesTrait;
use Illuminate\Support\Facades\Storage;
use Laravel\Lumen\Auth\Authorizable;

class User extends BaseModel implements AuthenticatableContract, AuthorizableContract
    {
    use Authenticatable, Authorizable, HasFactory, AttachmentTrait, SoftDeletesTrait;
    public $timestamps = true;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    // protected $fillable = [
    //     'username', 'email', 'api_token'
    // ];
    protected $guarded = [];
    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $casts = [
        'sex' => 'string',
    ];

    protected $hidden = [
        'password',
    ];
    public $attachmentkey = 'id';
    // avatar
    protected $appends = ['avatar', 'thumb_avatar'];
    public function getAvatarAttribute()
        {
        return $this->firstAttachment == null ? '#' : Storage::url($this->firstAttachment?->filepath);
        }
    public function getThumbAvatarAttribute()
        {
        return $this->firstAttachment == null ? '#' : Storage::url($this->firstAttachment->filethumbnail);
        }
    public function department()
        {
        return $this->belongsTo(Department::class);
        }
    public function role()
        {
        return $this->hasManyThrough(Role::class, UserRole::class, "user_id", 'id', 'id', 'role_id');
        }

    public function education()
        {
        return $this->belongsTo(Dic::class, "education_id", "key")->where(function ($q)
            {
            $q->where("code", 'Education');
            });
        }
    public function contactor_relation()
        {
        return $this->belongsTo(Dic::class, "contactor_relation_id", "key")->where(function ($q)
            {
            $q->where("code", 'Relation');
            });
        }
    public function marriage()
        {
        return $this->belongsTo(Dic::class, "marriage_id", "key")->where(function ($q)
            {
            $q->where("code", 'Marriage');
            });
        }
    public function rest()
        {
        return $this->belongsTo(Dic::class, "rest_id", "key")->where(function ($q)
            {
            $q->where("code", 'Rest');
            });
        }
    public function tokens()
        {
        return $this->hasMany(TemporaryToken::class);
        }

    }